package com.katze.boot.applet.asn1.adapter;

import com.katze.boot.applet.asn1.anlysis.ASN1Analysis;
import org.bouncycastle.asn1.*;

import java.nio.file.Files;
import java.nio.file.Path;

/**
 * 通用解析
 */
public class ASN1CommonAdapter implements BasicAdapter {
    private static ASN1CommonAdapter adapter = null;
    private Path file;
    private Path output;
    private String filename;

    public ASN1CommonAdapter() {}

    private void reset(Path file, String filename, Path output) {
        this.file = file;
        this.filename = filename;
        this.output = output;
    }

    public static ASN1CommonAdapter getInstance(Path file, String filename, Path output){
        if (adapter == null) adapter = new ASN1CommonAdapter();
        adapter.reset(file, filename, output);
        return adapter;
    }

    @Override
    public void run() {
        try (ASN1Analysis analysis = new ASN1Analysis(true, "@");
             ASN1InputStream asnStream = new ASN1InputStream(Files.newInputStream(file))) {
            analysis.config(this.filename).storage(output);
            ASN1Primitive primitive;
            while ((primitive = asnStream.readObject()) != null) {
                if (primitive instanceof ASN1ApplicationSpecific) {
                    primitive = ASN1ApplicationSpecific.getInstance(primitive.getEncoded()).getObject(BERTags.SET);
                } else if (primitive instanceof ASN1TaggedObject) {
                    primitive = ASN1TaggedObject.getInstance(primitive.getEncoded()).getObject();
                }
                analysis.save(primitive);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
